// user-tracker.js - 用户查询模块
// 等待apiService和Utils加载完成
function initUserTracker() {
    if (window.apiService && window.Utils) {
        const apiService = window.apiService;
        const Utils = window.Utils;

        class UserTracker {
    constructor() {
        this.initialize();
    }

    // 初始化
    initialize() {
        // 检查当前页面是否是追踪页面
        if (window.location.pathname.includes('/pages/user/track.html')) {
            this.initTrackingPage();
        }
    }

    // 初始化追踪页面
    async initTrackingPage() {
        // 尝试从URL参数或本地存储获取运单编号
        const trackingNumber = Utils.getUrlParam('trackingNumber') || Utils.storage.get('trackingNumber');

        if (trackingNumber) {
            // 填充输入框
            document.getElementById('tracking-number')?.setValue(trackingNumber);
            // 执行查询
            await this.trackPackage(trackingNumber);
        }

        // 绑定查询按钮事件
        document.getElementById('track-btn')?.addEventListener('click', async () => {
            const trackingNumber = document.getElementById('tracking-number')?.value;
            if (trackingNumber) {
                await this.trackPackage(trackingNumber);
            } else {
                Utils.showNotification('请输入运单编号', 'warning');
            }
        });
    }

    // 追踪包裹
    async trackPackage(trackingNumber) {
        try {
            // 显示加载状态
            this.showLoading(true);

            const response = await apiService.fetch(`/api/packages?id=${trackingNumber}`, {
                method: 'GET'
            });

            if (response.success && response.data) {
                this.renderPackageDetails(response.data);
                this.renderTrackingTimeline(response.data.updates);
                Utils.showNotification('查询成功', 'success');
            } else {
                this.renderNotFound();
                Utils.showNotification(response.message || '未找到包裹信息', 'error');
            }
        } catch (error) {
            this.renderNotFound();
            Utils.showNotification('查询失败，请稍后再试', 'error');
        } finally {
            // 隐藏加载状态
            this.showLoading(false);
        }
    }

    // 渲染包裹详情
    renderPackageDetails(pkg) {
        const detailsContainer = document.getElementById('package-details');
        if (!detailsContainer) return;

        // 状态样式映射
        const statusClassMap = {
            'pending': 'status-pending',
            'in-transit': 'status-in-transit',
            'delivered': 'status-delivered',
            'cancelled': 'status-pending'
        };

        detailsContainer.innerHTML = `
            <div class="package-info">
                <div class="package-header">
                    <h3 class="package-title">包裹详情</h3>
                    <span class="package-number">${pkg.id}</span>
                </div>
                <div class="package-details">
                    <div class="detail-item">
                        <div class="detail-label">状态</div>
                        <div class="detail-value">
                            <span class="current-status ${statusClassMap[pkg.status] || ''}">${this.getStatusText(pkg.status)}</span>
                        </div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">寄件人</div>
                        <div class="detail-value">${pkg.sender}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">收件人</div>
                        <div class="detail-value">${pkg.receiver}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">出发地</div>
                        <div class="detail-value">${pkg.origin}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">目的地</div>
                        <div class="detail-value">${pkg.destination}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">当前位置</div>
                        <div class="detail-value">${pkg.currentLocation}</div>
                    </div>
                    <div class="detail-item">
                        <div class="detail-label">预计送达</div>
                        <div class="detail-value">${pkg.estimatedDelivery}</div>
                    </div>
                    ${pkg.actualDelivery ? `
                    <div class="detail-item">
                        <div class="detail-label">实际送达</div>
                        <div class="detail-value">${pkg.actualDelivery}</div>
                    </div>
                    ` : ''}
                </div>
            </div>
        `;
    }

    // 渲染追踪时间线
    renderTrackingTimeline(updates) {
        const timelineContainer = document.getElementById('tracking-timeline');
        if (!timelineContainer) return;

        // 按时间倒序排列
        updates = [...updates].sort((a, b) => new Date(b.time) - new Date(a.time));

        let timelineHTML = `
            <div class="card">
                <div class="card-header">
                    <h2>物流追踪</h2>
                </div>
                <div class="timeline">
        `;

        updates.forEach((update, index) => {
            const isLeft = index % 2 === 0;
            const statusText = this.getStatusText(update.status);

            timelineHTML += `
                <div class="timeline-item ${isLeft ? 'timeline-left' : 'timeline-right'}">
                    <div class="timeline-content">
                        <div class="timeline-date">${Utils.formatDate(update.time)}</div>
                        <div class="timeline-status">${statusText}</div>
                        <div class="timeline-location">${update.location}</div>
                        <div class="timeline-description">${update.description}</div>
                    </div>
                </div>
            `;
        });

        timelineHTML += `
                </div>
            </div>
        `;

        timelineContainer.innerHTML = timelineHTML;
    }

    // 渲染未找到结果
    renderNotFound() {
        const detailsContainer = document.getElementById('package-details');
        const timelineContainer = document.getElementById('tracking-timeline');

        if (detailsContainer) {
            detailsContainer.innerHTML = `
                <div class="card">
                    <div class="card-header">
                        <h2>包裹详情</h2>
                    </div>
                    <div class="not-found">
                        <p>未找到包裹信息，请检查运单编号是否正确。</p>
                    </div>
                </div>
            `;
        }

        if (timelineContainer) {
            timelineContainer.innerHTML = '';
        }
    }

    // 显示/隐藏加载状态
    showLoading(show) {
        const loadingElement = document.getElementById('loading');
        if (loadingElement) {
            loadingElement.style.display = show ? 'block' : 'none';
        }
    }

    // 获取状态文本
    getStatusText(status) {
        const statusMap = {
            'pending': '待发货',
            'in-transit': '运输中',
            'delivered': '已送达',
            'cancelled': '已取消'
        };
        return statusMap[status] || status;
    }
}

// 初始化模块
const userTracker = new UserTracker();

// 暴露到全局作用域
window.userTracker = userTracker;
    }
}

// 立即检查是否加载完成
initUserTracker();

// 如果未加载完成，延迟500ms后重试
if (!window.apiService || !window.Utils) {
    setTimeout(initUserTracker, 500);
}